let WebIM = require("../../../../../utils/WebIM")["default"];
let msgType = require("../../../msgtype");

Component({
	properties: {
		username: {
			type: Object,
			value: {},
		},
		chatType: {
			type: String,
			value: msgType.chatType.SINGLE_CHAT,
		},
		enableLocation: {
			type: Boolean,
			value: false  //审核期入口级屏蔽：默认不启用位置分享,如果getLocation、chooseLocation 接口可以调用，则默认启用位置分享，否则默认不启用

        },
	},
	data: {

	},
	methods: {
		// 运行时检查定位接口可用性与授权
		checkLocationAvailability(needChoose, cb){
			const canGet = !!wx.canIUse && wx.canIUse('getLocation');
			const canChoose = !!wx.canIUse && wx.canIUse('chooseLocation');
			if(!canGet || (needChoose && !canChoose)){
				wx.showModal({
					title: '提示',
					content: '当前版本未开通定位/选点能力，请稍后重试或跳过位置分享',
					showCancel: false
				});
				typeof cb === 'function' && cb(false, { reason: 'api_unavailable' });
				return;
			}
			wx.getSetting({
				success: (res) => {
					const auth = res.authSetting && res.authSetting['scope.userLocation'];
					if(auth === false){
						wx.showModal({
							title: '提示',
							content: '未授权位置信息，您可在设置中开启，或跳过位置分享',
							showCancel: false
						});
						cb && cb(false, { reason: 'denied' });
					}else{
						cb && cb(true);
					}
				},
				fail: () => {
					cb && cb(false, { reason: 'get_setting_fail' });
				}
			});
		},
		isGroupChat(){
			return this.data.chatType == msgType.chatType.CHAT_ROOM;
		},

		getSendToParam(){
			return this.isGroupChat() ? this.data.username.groupId : this.data.username.your;
		},

		sendLocation(){
			// 审核期入口级屏蔽：默认不启用位置分享
			if(!this.data.enableLocation){
				wx.showToast({ title: '本版本暂不提供位置功能', icon: 'none' });
				return;
			}
			var me = this;
			this.checkLocationAvailability(true, function(ok){
				if(!ok) return;
				wx.authorize({
					scope: "scope.userLocation",
					fail(){
						wx.showToast({
							title: "已拒绝",
							icon: "none",
						});
					},
					success(){
						wx.chooseLocation({
							fail(){
								console.log(arguments);
							},
							complete(){
								console.log(arguments);
							},
							success(respData){
								var id = WebIM.conn.getUniqueId();
								var msg = new WebIM.message(msgType.LOCATION, id);
								msg.set({
									msg: "",
									from: me.data.username.myName,
									to: me.getSendToParam(),
									roomType: false,
									lng: respData.longitude,
									lat: respData.latitude,
									addr: respData.address,
									chatType: me.data.chatType,
									success(id, serverMsgId){
									}
								});
								if(me.data.chatType == msgType.chatType.CHAT_ROOM){
									msg.setGroup("groupchat");
								}
								WebIM.conn.send(msg.body);
								me.triggerEvent(
									"newLocationMsg",
									{
										msg: msg,
										type: msgType.LOCATION
									},
									{
										bubbles: true,
										composed: true
									}
								);
							}
						});
					}
				});
			});
		},
	},
});
